import Vue from 'vue'
import VueRouter from 'vue-router'

import index from '../views/index'
import Administration from '../views/Administration'
import Login from "../views/Login"
import Register from "../views/Register"
import User from "../views/User"
import News from "../views/News"
import EditingNews from "../views/EditingNews"
import Topic from "../views/Topic"
import IndexNews from "../views/IndexNews"
import NewsDetail from "../views/NewsDetail"
import Search from "../views/Search"
import Comments from "../views/Comments"
import ForgetPwd from "../views/ForgetPwd"

//解决重复跳转报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [{
  path: '/',
  redirect: '/index'
}, {
  path: '/index',
  component: index,
  children: [{
    path: '/',
    redirect: '/IndexNews'
  }, {
    path: '/indexNews',
    component: IndexNews
  }, {
    path: '/topic',
    component: Topic
  }, {
    path: '/newsDetail',
    component: NewsDetail
  },{
    path: '/search',
    component: Search
  }]
}, {
  path: '/administration',
  component: Administration,
  children: [{
    path: '/',
    redirect: '/user'
  }, {
    path: '/user',
    component: User
  }, {
    path: '/news',
    component: News
  }, {
    path: '/editingNews',
    component: EditingNews
  },{
    path: '/comments',
    component: Comments
  }]
}, {
  path: '/login',
  component: Login
}, {
  path: '/register',
  component: Register
},{
  path: '/forgetPwd',
  component: ForgetPwd
}]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if (to.matched[0].path === '/administration') {
    const adminToken = window.sessionStorage.getItem('adminToken')
    if (!adminToken) return next('/login')
  }
  next()
})

export default router
